package com.security.config.security;

import com.security.config.filter.JWTAuthenticationEntryPoint;
import com.security.config.filter.JWTAuthenticationFilter;
import com.security.config.filter.JWTAuthorizationFilter;
import com.security.system.service.SysUserService;
import com.security.utils.JwtTokenUtil;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.annotation.Resource;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    SysUserService sysUserService;

    @Resource
    PasswordEncoder passwordEncoder;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    AccessDeniedHandler ajaxAccessDeniedHandler;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(sysUserService).passwordEncoder(passwordEncoder);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .antMatchers(HttpMethod.OPTIONS)
                .antMatchers("/user/test")
                .antMatchers("/excel");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .addFilter(new JWTAuthenticationFilter(authenticationManager(),jwtTokenUtil))
                .addFilter(new JWTAuthorizationFilter(authenticationManager(),jwtTokenUtil))
                .authorizeRequests()
                .anyRequest().access("@arbcServiceFilter.hasPermission(request,authentication)")
                .and()
                // 不需要session
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .exceptionHandling()
                .accessDeniedHandler(ajaxAccessDeniedHandler)
                .authenticationEntryPoint(new JWTAuthenticationEntryPoint());
    }


}
